﻿using Sidvall.Serialization;
using System.Linq;

namespace Sidvall.WorkItemManager.Data
{
	public class SensorValueCollection : System.Collections.ObjectModel.Collection<SensorValue>
	{
		#region Public Members

		#region FindSensor

		public SensorValue FindSensor(string name)
		{
			if (name == null)
				return null;
			return (from o in this
					where o.Name.Equals(name, System.StringComparison.OrdinalIgnoreCase)
					select o).FirstOrDefault();
		}

		#endregion
		#region UpdateSensor

		public SensorValue UpdateSensor(string name, string value, System.DateTime? valueTimestamp)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return null;
			item.Value = value;
			item.ValueTimestamp = valueTimestamp;

			return item;
		}

		#endregion
		#region ValueToBoolean

		public bool ValueToBoolean(string name, bool defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value.ToBoolean(defaultValue);
		}

		#endregion
		#region ValueToDecimal

		public decimal ValueToDecimal(string name, decimal defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value.ToDecimal(defaultValue);
		}

		#endregion
		#region ValueToDouble

		public double ValueToDouble(string name, double defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value.ToDouble(defaultValue);
		}

		#endregion
		#region ValueToByte

		public byte ValueToByte(string name, byte defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value.ToByte(defaultValue);
		}

		#endregion
		#region ValueToInt16

		public short ValueToInt16(string name, short defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value.ToInt16(defaultValue);
		}

		#endregion
		#region ValueToInt32

		public int ValueToInt32(string name, int defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value.ToInt32(defaultValue);
		}

		#endregion
		#region ValueToInt64

		public long ValueToInt64(string name, long defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value.ToInt64(defaultValue);
		}

		#endregion
		#region ValueToString

		public string ValueToString(string name, string defaultValue)
		{
			SensorValue item;

			item = FindSensor(name);
			if (item == null)
				return defaultValue;
			return item.Value;
		}

		#endregion

		#endregion
	}
}
